<template>
<div>
<!-- 面包屑 -->
<el-breadcrumb separator-class="el-icon-arrow-right">
<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>菜单管理</el-breadcrumb-item>
<el-breadcrumb-item>餐品管理</el-breadcrumb-item>
<!-- <el-breadcrumb-item>promotion detail</el-breadcrumb-item> -->
</el-breadcrumb>

 <!-- 白色区域内容 -->
    <div class="page_content">
      <div class="flex">
        <div class="input_box">
          <el-input v-model="input3" placeholder="按照分类名搜索" class="input-with-select">
            <template #append>
              <el-button @click="searchByName"><i class="el-icon-search"></i><el-icon><Search /></el-icon></el-button>
            </template>
          </el-input>
        </div>

       
        <!-- //添加用户窗口 -->
        <el-dialog title="添加分类信息" v-model="addDialogVisible">
          <el-form :model="addForm" label-position="left" label-width="80px">
            <el-form-item label="分类名">
              <el-input v-model="addForm.name"></el-input>
            </el-form-item>
             <el-form-item label="加入活动">
                 <el-switch v-model="addForm.isActivity"></el-switch>
            </el-form-item>
            <el-form-item label="启用">
                <el-switch v-model="addForm.isUse"></el-switch>
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="addForm.text"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser(addForm)">确 定</el-button>
          </div>
        </el-dialog>

        <div class="flex">
      
        
        <!-- 增加一个删除的按钮 -->
        <el-button type="danger" @click="showDeleteCheckbox=!showDeleteCheckbox">{{ showDeleteCheckbox ? '取消删除' : '删除' }}</el-button>
          <el-button type="button" @click="addDialogVisible = true" class="myButton">新建</el-button>
        </div>
      </div>
      <!-- 显示复选框 -->
      <el-table :data="tableData" stripe style="width: 100%"  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="showDeleteCheckbox"></el-table-column>
        <el-table-column prop="id" label="id" width="100" />
        <el-table-column prop="name" label="分类名" width="180" />
        <el-table-column prop="text" label="描述" width="180" />
        <el-table-column prop="createdTime" label="创建时间" />
        <el-table-column prop="isActivity" label="活动" :formatter="formatIsActivity" />
        <el-table-column prop="isUse" label="启用" :formatter="formatIsUse" />

        <el-table-column fixed="right" label="操作" width="180">
                <template #default="{row}">
                <el-button type="button" @click="handleEdit(row)" class="myButton1">编辑</el-button>
                </template>
        </el-table-column>

      </el-table>

      <!-- 删除按钮 -->
      <div style="text-align: center; margin-top: 20px;" v-if="showDeleteCheckbox">
        <el-button type="danger" @click="deleteSelectedRows()">删除所选</el-button>
      </div>
    </div>

    <!-- 编辑窗口 -->
    <el-dialog title="编辑分类信息" v-model="editDialogVisible">
       <el-form :model="editForm" label-position="top" label-width="80px">
            <el-form-item label="分类名">
            <el-input v-model="editForm.name"></el-input>
            </el-form-item>
            <el-form-item label="加入活动">
            <el-switch v-model="editForm.isActivity"></el-switch>
            </el-form-item>
            <el-form-item label="描述">
            <el-input v-model="editForm.text"></el-input>
            </el-form-item>
            <el-form-item label="创建时间">
            <el-input v-model="editForm.createdTime" disabled></el-input>
            </el-form-item>
            <el-form-item label="启用">
            <el-switch v-model="editForm.isUse"></el-switch>
            </el-form-item>
        </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button class="myButton1" type="primary" @click="submitEdit">确 定</el-button>
      </div>
    </el-dialog>
    <div class="pagination">
    <el-pagination v-model:current-page="page" v-model:page-size="size" :page-sizes="[5,10,20,30]" :small="small" :disabled="disabled"
      :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>

  </div>
</template>

<script setup>
import { h, onMounted, reactive, ref } from 'vue';
import axios from '../../utils/axios';
import { ElMessageBox, ElMessage } from 'element-plus';

let tableData = reactive([]);
const input3 = ref('');
//分页设置
let page = 1;
let size = 5;
const small = ref(false)
const disabled = ref(false)
const background = ref(false)
const total = ref(0)

const editDialogVisible = ref(false);
const addDialogVisible = ref(false);
const editForm = reactive({
  id:'',
  name: '',
  isActivity: 0,
  text: '',
  createdTime: '',
  isUse: 1,
  deleted: '0',
});
const addForm = reactive({
    id:'',
   name: '',
  isActivity: false,
  text: '',
  isUse: true
});
const showDeleteCheckbox = ref(false);
let selectedRows = reactive([]);
let seletionIds = reactive([]);

const handleSizeChange = (val) => {
  size = val;
  refreshTableData();
} 
const handleCurrentChange = (val) => {
  page = val;
  refreshTableData();
}

// const handleDetail = (row) => {
//   ElMessageBox({
//     title: '菜单详情',
//     message: h('div', null, [
//       h('p', null, `ID: ${row.userId}`),
//       h('p', null, `电话：${row.mobile}`),
//       h('p', null, `密码：${row.password}`),
//     ]),
//   });
// };

const formatIsActivity = (row) => {
return row.isActivity ? '否' : '是';
};

const formatIsUse = (row) => {
return row.isUse ? '否' : '是';
};

const handleEdit = (row) => {
  // 对editForm进行初始化
  editForm.id = row.id;
  editForm.name = row.name;
  editForm.isActivity = (row.isActivity === 0);
  editForm.text = row.text;
  editForm.createdTime = row.createdTime;
  editForm.isUse = (row.isUse === 0);
  editDialogVisible.value = true;
};

const cancelEdit = () => {
  editDialogVisible.value = false;
  resetEditForm();
};

const submitEdit = () => {
// 将开关的值进行转换
    editForm.isActivity = editForm.isActivity ? 0 : 1;
    editForm.isUse = editForm.isUse ? 0 : 1;
  axios.put('/category/', editForm).then((res) => {
    console.log('提交修改：', editForm);
    console.log("res为：")
    console.log(res) 
    ElMessage.success('分类数据修改成功')
    refreshTableData();
    editDialogVisible.value = false;
  }).catch((err) => {
    console.error(err);
    // 使用element-plus的message组件
    ElMessage.error('提交失败，请稍后再试');
  });
};

const resetEditForm = () => {
  editForm.id = tableData[tableData.length - 1].id + 1;
  editForm.name = '';
  editForm.isActivity = 0;
  editForm.text = '';
  editForm.isUse = 1;
};

const handleSelectionChange = (value) => {
  selectedRows = reactive([]);
  selectedRows.value = value;
};


//根据名字模糊查询
const searchByName = () => {
  if (!input3.value) {
   refreshTableData();
  } else {
    axios.get(`/category/search/${input3.value}`).then((res) => {
      console.log('提交查询：', input3.value);
      console.log('res为：', res);
      console.log('res.data:', res.data);
      if (res.code === 200) {
        const result = res.data;
        tableData.splice(0, tableData.length);
        for (let i in result) tableData.push(result[i]);
        console.log(',tableData：', tableData);
      } else {
        ElMessage.error(res.msg);
      }
    }).catch((err) => {
      console.error(err);
      ElMessage.error('获取分类列表失败');
    });
  }
};





const deleteSelectedRows = () => {
  const count = selectedRows.value.length;
  if (count > 0) {
    ElMessageBox.confirm(`已选择 ${count} 条数据，是否确认删除？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      const ids = selectedRows.value.map((row) => row.id);
      for (let id of ids) {
        axios.delete('/category/' + id).then((res) => {
          console.log("删除后的数据如下");
          console.log(res);
          console.log(res.code);
          if (res.code == 200) {
            showDeleteCheckbox.value = false;
            selectedRows.value = [];
            ElMessage.success('删除成功！');
            refreshTableData();
          } else {
            ElMessage.error('删除失败！');
          }
        }).catch((err) => {
          console.error(err);
          ElMessage.error('删除失败，请稍后再试');
        });
      }
    }).catch(() => {
      // do nothing
    });
  }
};


//添加菜单的方法
const addUser = (addForm) => {
  addDialogVisible.value = true;
   addForm.isActivity = addForm.isActivity ? 0 : 1;
  addForm.isUse = addForm.isUse ? 0 : 1;
   console.log("添加分类addForm为：",addForm)
  axios.post('/category/',addForm).then((res) => {

    console.log("添加分类res为：")
    console.log(res)
    if (res.code == 200) {
      tableData.push(res.data);
      refreshTableData();
      ElMessage.success("添加分类成功");
       addDialogVisible.value = false;
    } else {
      ElMessage.error(res.msg);
    }
  }).catch((err) => {
    console.log(err);
    ElMessage.error('添加分类失败');
  });
};

//初始化请求数据
const refreshTableData = () => {
  axios.get(`/category/list/${page}/${size}`).then((res) => {
    console.log("res为：")
    console.log(res)
    if (res.code == 200) {

      tableData.splice(0, tableData.length);
      total.value = res.data.total
      const result = res.data.list;
      for (let i in result) tableData.push(result[i]);
       console.log("tabl0eData")
      console.log(tableData)
    } else {
      ElMessage.error(res.msg);
    }
  }).catch((err) => {
    console.log(err);
    ElMessage.error('获取菜单列表失败');
  });
};

onMounted(() => {
  refreshTableData();
});

</script>

<style scoped>
.page_content {
  margin: 20px;
  padding: 20px;
  background-color: white;
}

.flex {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  /* margin-right: 5px; */
  padding: 10px;
}

.myButton {
  margin-right: 10px;
  height: 32px;
  line-height: 30px;
  background-color: #5ad2ad;
  border-color: #8ddc88;
  color: white;
  float:right;
}

.myButton1 {
  margin-right: 70px;
  height: 32px;
  line-height: 30px;
  background-color: #70a6e0;
  border-color: #80b4ec;
  color: white;
  float:right;
}
.input_box .el-input {
  width: 250px;
}

.el-button.link {
  color: #8ddc88;
  background-color: transparent;
  border-color: transparent;
}

.dialog-footer {
  text-align: right;
}
</style>